// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

using System;
using System.Linq;
using System.IdentityModel.Tokens;
using Microsoft.IdentityModel.Claims;
using Microsoft.IdentityModel.Protocols.WSIdentity;
using Microsoft.IdentityModel.Tokens;
using IssueVision.ST_Sts.EntityModel;
using IssueVision.ST_Sts.Helper;

public class CustomUserNamePasswordTokenHandler : UserNameSecurityTokenHandler
{
    public override bool CanValidateToken
    {
        get
        {
            return true;
        }
    }

    public override ClaimsIdentityCollection ValidateToken(SecurityToken token)
    {
        UserNameSecurityToken usernameToken = token as UserNameSecurityToken;

        if (usernameToken == null)
        {
            throw new ArgumentException("The security token is not a valid username security token.", "token");
        }

        using (AuthenticationEntities context = new AuthenticationEntities())
        {
            User foundUser = context.Users.FirstOrDefault(n => n.Name == usernameToken.UserName);

            if (foundUser != null)
            {
                // generate password hash
                string passwordHash = HashHelper.ComputeSaltedHash(usernameToken.Password, foundUser.PasswordSalt);

                if (string.Equals(passwordHash, foundUser.PasswordHash, StringComparison.Ordinal))
                {
                    IClaimsIdentity identity = new ClaimsIdentity();
                    identity.Claims.Add(new Claim(WSIdentityConstants.ClaimTypes.Name, usernameToken.UserName));

                    return new ClaimsIdentityCollection(new[] { identity });
                }
            }
            throw new UnauthorizedAccessException("The username/password is incorrect");
        }
    }
}